package com.supplychain.scm.core.framework.chain.base;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName AbstractChain
 * @Description 抽象职责链(职责链使用动态配置)
 * @createTime 09:48:00 2022/10/15
 */
@Slf4j
public abstract class AbstractChain<T,R> implements IChain<T,R> {

	/**
	 * 业务处理之前处理
	 * @param t
	 * @return
	 */
	protected Object beforeHandler(T t){
		return null;
	}
	/**
	 * 策略业务处理方法定义
	 * @param t
	 * @return
	 */
	protected R handler(T t){
		throw new UnsupportedOperationException();
	}
	/**
	 * 业务处理之后处理
	 * @param t
	 * @param r
	 * @return
	 */
	protected Object afterHandler(T t,R r){
		return null;
	}
	/**
	 * 异常处理器
	 * @param t
	 * @return
	 */
	protected Object exceptionHandler(T t,R r){
		return null;
	}
	/**
	 * 最终处理器
	 * @param t
	 * @return
	 */
	protected Object finallyHandler(T t,R r){
		return null;
	}
	public R chainHandler(T t){
		R r = null;
		try {
			this.beforeHandler(t);
			r = this.handler(t);
			this.afterHandler(t,r);
		} catch (Exception e) {
			this.exceptionHandler(t,r);
			log.warn("职责链处理器发生异常:{}", ExceptionUtils.getStackTrace(e));
			throw e;
		} finally {
			this.finallyHandler(t,r);
		}
		return r;
	}
}
